# 引入模块--导包
import requests
from requests import utils
import re
from unit_tools.handle_data.yaml_handler import read_yaml, write_yaml
from unit_tools.log_util.recordlog import logs
import json


class SendRequests:
    def __init__(self):
        # 占位符
        pass

    @classmethod
    def _text_encode(cls, res_text):
        match = re.search(r"\\u[0-9a-fA-F]{4}", res_text)
        if match:
            result = res_text.encode().decode('unicode_escape')
        else:
            result = res_text
        return result


    def send_request(self, **kwargs):
        session = requests.Session()
        response = None
        try:
            response = session.request(**kwargs)
            set_cookie = requests.utils.dict_from_cookiejar(response.cookies)
            if set_cookie:
                write_yaml({'Cookie': set_cookie})
            res = self._text_encode(response.text)
            print(f'接口实际返回结果：{res}')
        except requests.exceptions.ConnectionError:
            logs.error("接口请求异常，可能是request的链接数过多或者速度过快导致程序报错！")
        except requests.exceptions.RequestException as e:
            logs.error(f'请求异常，请检查系统或数据是否正常！错误信息为：{e}')
        return response

    def execute_api_request(self, api_name, url, method, headers, case_name, cookies=None, files=None, **kwargs):
        logs.info(f'接口名称：{api_name}')
        logs.info(f'请求地址：{url}')
        logs.info(f'请求方式：{method.upper()}')
        # logs.info(f'请求方式：{method}')
        logs.info(f'请求头：{headers}')
        logs.info(f'测试用例名：{case_name}')
        logs.info(f'cookies值：{cookies}')
        yaml_params_type = kwargs.keys()
        if kwargs and ('data' in yaml_params_type or 'json' in yaml_params_type or 'params' in yaml_params_type):
            params_type = list(kwargs.keys())[0]
            logs.info(f'参数类型：{params_type}')
            params = json.dumps(list(kwargs.values())[0], ensure_ascii=False)
            logs.info(f'请求参数：{params}')
        response = self.send_request(method=method, url=url, headers=headers, cookies=cookies, files=files, timeout=10,
                                     verify=False, **kwargs)
        return response


if __name__ == '__main__':
    from unit_tools.handle_data.configParse import ConfigParser
    host = ConfigParser().get_host('host')
    data = read_yaml('../testcase/login/login.yaml')[0]
    url = host + data['baseInfo']['url']
    method = data['baseInfo']['method']
    header = data['baseInfo']['header']
    req_data = data['testCase'][0]['data']
    send = SendRequests()
    res = send.execute_api_request(api_name=None, url=url, method=method, header=None, case_name=None,
                                   data=req_data)
    res_json = res.json()
    token = res_json['token']
    user_id = res_json['userId']
    write_yaml({'token': token, 'userId': user_id})